package com.melodyframe.common.context;

import java.util.LinkedHashMap;
import java.util.Map.Entry;

public class CommonContext implements Context {
	private final static String					DEFAULT_CONTEXT_KEY	= "#!default#";
	private LinkedHashMap<String, ScopeContext>	scopeContexts;

	public CommonContext() {
		this.scopeContexts = new LinkedHashMap<String, ScopeContext>();
		this.addScope(DEFAULT_CONTEXT_KEY, new HashContext());
	}

	@Override
	public void addScope(String scope, ScopeContext context) {
		this.scopeContexts.put(scope, context);
	}

	@Override
	public boolean containsKey(Object key) {
		for (Entry<String, ScopeContext> scopeEntry : this.scopeContexts
				.entrySet()) {
			if (scopeEntry.getValue().containsKey(key)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Object get(Object key) {
		for (Entry<String, ScopeContext> scopeEntry : this.scopeContexts
				.entrySet()) {
			if (scopeEntry.getValue().containsKey(key)) {
				return scopeEntry.getValue().get(key);
			}
		}
		return null;
	}

	@Override
	public Object get(Object key, String scope) {
		ScopeContext scopeContext = this.getScope(scope);
		if (null != scopeContext) {
			return scopeContext.get(key);
		} else {
			return null;
		}

	}

	@Override
	public Object put(String key, Object value) {
		return this.put(key, value, DEFAULT_CONTEXT_KEY);
	}

	@Override
	public Object put(String key, Object value, String scope) {
		ScopeContext scopeContext = this.getScope(scope);
		if (null != scopeContext) {
			return scopeContext.put(key, value);
		} else {
			return null;
		}
	}

	public ScopeContext getScope(String scope) {
		if (null == this.scopeContexts || null == scope) {
			return null;
		}
		return this.scopeContexts.get(scope);
	}
}
